<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Hash;

class TenantUser extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'tenant_id',
        'username',
        'email',
        'name',
        'phone',
        'password',
        'role',
        'status',
        'last_login_at',
        'last_login_ip',
        'created_by'
    ];

    protected $hidden = [
        'password',
        'remember_token'
    ];

    protected $casts = [
        'id' => 'string',
        'tenant_id' => 'string',
        'email_verified_at' => 'datetime',
        'last_login_at' => 'datetime'
    ];

    public function getIdAttribute($value): string
    {
        return (string) $value;
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = static::generateSnowflakeId();
            }
        });
    }

    public static function generateSnowflakeId(): string
    {
        $timestamp = (int) (microtime(true) * 1000);
        $machineId = mt_rand(0, 1023);
        $sequence = mt_rand(0, 4095);

        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;

        return (string) $snowflakeId;
    }

    // 关联租户
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    // 关联创建人
    public function createdBy()
    {
        return $this->belongsTo(AdminUser::class, 'created_by');
    }

    // 租户内角色常量
    const TENANT_ROLE_OWNER = 'owner';          // 租户所有者
    const TENANT_ROLE_ADMIN = 'admin';          // 租户管理员
    const TENANT_ROLE_OPERATOR = 'operator';    // 操作员
    const TENANT_ROLE_VIEWER = 'viewer';        // 查看员

    // 用户状态常量
    const STATUS_ACTIVE = 'active';             // 激活
    const STATUS_INACTIVE = 'inactive';         // 停用
    const STATUS_LOCKED = 'locked';             // 锁定

    // 获取租户角色显示名称
    public function getTenantRoleDisplayAttribute()
    {
        $roles = [
            self::TENANT_ROLE_OWNER => '租户所有者',
            self::TENANT_ROLE_ADMIN => '租户管理员',
            self::TENANT_ROLE_OPERATOR => '操作员',
            self::TENANT_ROLE_VIEWER => '查看员'
        ];

        return $roles[$this->tenant_role] ?? $this->tenant_role;
    }

    // 获取状态显示名称
    public function getStatusDisplayAttribute()
    {
        $statuses = [
            self::STATUS_ACTIVE => '激活',
            self::STATUS_INACTIVE => '停用',
            self::STATUS_LOCKED => '锁定'
        ];

        return $statuses[$this->status] ?? $this->status;
    }

    // 设置密码
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    // 更新最后登录信息
    public function updateLastLogin($ip = null)
    {
        $this->last_login_at = now();
        $this->last_login_ip = $ip;
        $this->save();
    }

    // 检查是否有指定权限
    public function hasPermission($permission)
    {
        // 租户所有者拥有所有权限
        if ($this->tenant_role === self::TENANT_ROLE_OWNER) {
            return true;
        }

        // 根据角色判断权限
        $rolePermissions = [
            self::TENANT_ROLE_ADMIN => [
                'task.create', 'task.edit', 'task.delete', 'task.view',
                'freelancer.view', 'settlement.view', 'invoice.create',
                'employee.create', 'employee.edit', 'employee.view'
            ],
            self::TENANT_ROLE_OPERATOR => [
                'task.create', 'task.edit', 'task.view',
                'freelancer.view', 'settlement.view'
            ],
            self::TENANT_ROLE_VIEWER => [
                'task.view', 'freelancer.view', 'settlement.view'
            ]
        ];

        return in_array($permission, $rolePermissions[$this->tenant_role] ?? []);
    }
}
